<!--
 * @Descripttion: damage报损报溢新增
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 20:26:23
 * @LastEditors: cxguo
 * @LastEditTime: 2019-10-04 11:52:01
 -->
<template>
  <div class="wapper">
    <!-- defaultCheckedKeys: {{ defaultCheckedKeys }} <br>
    defaultExpandedKeys: {{ defaultExpandedKeys }} -->
    <el-tree
      ref="tree"
      style="width:1000px;"
      :data="permissionTreeData"
      show-checkbox
      node-key="perId"
      :default-expanded-keys="defaultExpandedKeys"
      :default-checked-keys="defaultCheckedKeys"
      :props="defaultProps"
    />
  </div>
</template>

<script>
import { oftenuse } from '@/libs/mixins'
import { getpermissionsByRoleId, getpermissionsAll } from '@/api/sys/permission.js'
import toArrayTree from 'xe-utils/methods/array/toArrayTree'

export default {
  name: 'PermissionTree',
  mixins: [oftenuse],
  props: {
    roleData: {
      type: Object,
      default: () => { return {} }
    }
  },
  data() {
    return {
      permissionData: [],
      permissionTreeData: [],
      permissionDataWithRole: [], // 角色的权限
      defaultProps: {
        children: 'children',
        label: 'perName'
      }
    }
  },
  computed: {
    defaultCheckedKeys: function() {
      const permissionDataWithRole = this.permissionDataWithRole
      return permissionDataWithRole.map(item => { return item.perId })
    },
    defaultExpandedKeys: function() {
      const permissionData = this.permissionData
      const parentPermission = permissionData.filter(item => { return item.perParent === null })
      return parentPermission.map(item => { return item.perId })
    }
  },
  created() {
    this.initData()
  },
  methods: {
    btnSaveAdd() {
    },
    btnSave() {
    },
    /**
     * 获取选中的Nodes
     */
    getCheckedNodes() {
      return this.$refs.tree.getCheckedNodes()
    },
    // API
    listPermissionAllData() {
      return getpermissionsAll().then(res => {
        const data = res.data.data
        data.forEach(element => {
          delete element.pid
          delete element.pparent
        })
        if (res.data.flag) {
          const options = {
            key: 'perId',
            parentKey: 'perParent'
          }
          this.permissionData = res.data.data
          this.permissionTreeData = toArrayTree(res.data.data, options)
        }
      })
    },
    initRolePermissions() {
      const roleId = this.roleData.roleId
      if (roleId) this.listPermissionByRoleId(roleId)
    },
    listPermissionByRoleId(roleId) {
      return getpermissionsByRoleId(roleId).then(res => {
        this.permissionDataWithRole = []
        if (res.data.flag) this.permissionDataWithRole = res.data.data
      })
    },
    initData() {
      this.listPermissionAllData()
      this.initRolePermissions()
    }
  }
}
</script>

<style scoped>
.wapper{
  height: 500px; overflow: auto;
}
</style>
